package service;

import dao.JPADAOFactory;
import dao.exception.AlreadyEntityExistsException;
import dao.exception.NotEntityFoundException;
import entity.Formulario;
import javax.persistence.EntityManager;
import service.exception.DuplicateObjectException;
import service.exception.ObjectNotFoundException;
import valueObject.FormularioVO;



public class FormularioService extends AbstractService<FormularioVO, Formulario> {

    @Override
    public int create(FormularioVO valueObject, EntityManager em) throws DuplicateObjectException {
        try {
            Formulario formulario = valueObject.toEntity();
            JPADAOFactory.getInstance().getFormularioDAO().create(formulario, em);
            return formulario.getId();
        } catch (AlreadyEntityExistsException ex) {
            throw new DuplicateObjectException();
        }
        
    }

    @Override
    public FormularioVO findById(int id, EntityManager em) throws ObjectNotFoundException {
        try {
            return JPADAOFactory.getInstance().getFormularioDAO().findById(id, em).toValueObject();
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public void update(FormularioVO valueObject, EntityManager em) throws ObjectNotFoundException {
        try {
            Formulario formulario = JPADAOFactory.getInstance().getFormularioDAO().findById(valueObject.getId(), em);
            formulario = valueObject.toEntity();
            JPADAOFactory.getInstance().getFormularioDAO().update(formulario, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public void delete(int id, EntityManager em) throws ObjectNotFoundException {
        try {
            Formulario formulario = JPADAOFactory.getInstance().getFormularioDAO().findById(id, em);
            JPADAOFactory.getInstance().getFormularioDAO().delete(formulario, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }
    
    public FormularioVO findFormularioActual(EntityManager em) throws ObjectNotFoundException{
        try {
            return JPADAOFactory.getInstance().getFormularioDAO().findFormularioActual(em).toValueObject();
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

}
